import { login } from "@/api/user";
import { resetRouter } from "@/router";
import {
  getToken,
  getUserInfo,
  removeToken,
  removeUser,
  setToken,
  setUserInfo,
} from "@/utils/auth";

const getDefaultState = () => {
  return {
    accesstoken: getToken(),
    name: getUserInfo("userName"),
    avatar: getUserInfo("avatar"),
    userId: getUserInfo("userId"),
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, accesstoken) => {
    state.accesstoken = accesstoken;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_USERID: (state, userId) => {
    state.userId = userId;
  },
};

const actions = {
  login({ commit }, userInfo) {
    const { mobilePhoneNumber, passWord } = userInfo;
    return new Promise((resolve, reject) => {
      login({ mobilePhoneNumber: mobilePhoneNumber.trim(), passWord })
        .then((response) => {
          let { accesstoken, mobilePhoneNumber } = response.data;
          commit("SET_TOKEN", accesstoken);
          setToken(accesstoken);
          commit("SET_USERID", mobilePhoneNumber);
          setUserInfo({ mobilePhoneNumber });
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      resetRouter();
      removeToken();
      removeUser();
      commit("SET_TOKEN", "");
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("SET_TOKEN", "");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
